package com.atguigu.gmall.realtime.app.dim;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.func.DimSinkFunction;
import com.atguigu.gmall.realtime.app.func.TableProcessFunction;
import com.atguigu.gmall.realtime.beans.TableProcess;
import com.atguigu.gmall.realtime.common.GmallConfig;
import com.atguigu.gmall.realtime.utils.HbaseUtil;
import com.atguigu.gmall.realtime.utils.MyKafkaUtil;
import com.ververica.cdc.connectors.mysql.source.MySqlSource;
import com.ververica.cdc.connectors.mysql.table.StartupOptions;
import com.ververica.cdc.debezium.JsonDebeziumDeserializationSchema;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.streaming.api.datastream.BroadcastConnectedStream;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.hadoop.hbase.client.Connection;

import java.util.Properties;

/**
 * @author Felix
 * @date 2023/11/7
 */
public class MyApp extends BaseApp{
    public static void main(String[] args) throws Exception {
        MyApp app = new MyApp();
        app.base(args);
    }

    @Override
    public void biz(StreamExecutionEnvironment env) {
        //TODO 3.从kafka主题中读取数据
        //3.1 声明消费的主题以及消费者组
        String topic = "topic_db";
        String groupId = "dim_app_group";
        //3.2 创建消费者对象
        KafkaSource<String> kafkaSource = MyKafkaUtil.getKafkaSource(topic, groupId);
        //3.3 消费数据  封装为流
        DataStreamSource<String> kafkaStrDS
            = env.fromSource(kafkaSource, WatermarkStrategy.noWatermarks(), "Kafka Source");
        //TODO 4.对业务流中数据进行类型转换并进行简单的ETL    jsonStr->jsonObj
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaStrDS.process(
            new ProcessFunction<String, JSONObject>() {
                @Override
                public void processElement(String jsonStr, Context ctx, Collector<JSONObject> out) throws Exception {
                    try {
                        JSONObject jsonObj = JSON.parseObject(jsonStr);
                        String type = jsonObj.getString("type");
                        if(!"bootstrap-start".equals(type)&&!"bootstrap-complete".equals(type)){
                            out.collect(jsonObj);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        );

        // jsonObjDS.print(">>>>");


        //TODO 5.使用FlinkCDC读取配置表中的配置信息
        //5.1 创建MySqlSource数据源对象
        Properties props = new Properties();
        props.setProperty("useSSL", "false");
        MySqlSource<String> mySqlSource = MySqlSource.<String>builder()
            .hostname("hadoop102")
            .port(3306)
            .databaseList("gmall0529_config") // set captured database
            .tableList("gmall0529_config.table_process_dim") // set captured table
            .username("root")
            .password("123456")
            .jdbcProperties(props)
            .serverTimeZone("Asia/Shanghai")
            .deserializer(new JsonDebeziumDeserializationSchema())
            .startupOptions(StartupOptions.initial())
            .build();

        //5.2 封装为流
        DataStreamSource<String> mysqlStrDS
            = env.fromSource(mySqlSource, WatermarkStrategy.noWatermarks(), "mySql_source");
        // mysqlStrDS.print(">>>");
        //TODO 6.对配置流中数据类型进行转换    jsonStr->实体类对象
        SingleOutputStreamOperator<TableProcess> tableProcessDS = mysqlStrDS.map(
            new MapFunction<String, TableProcess>() {
                @Override
                public TableProcess map(String jsonStr) throws Exception {
                    //为了处理方便，将json字符串转换为json对象
                    JSONObject jsonObj = JSON.parseObject(jsonStr);
                    //获取对配置表进行的操作类型
                    String op = jsonObj.getString("op");
                    TableProcess tableProcess = null;
                    if ("d".equals(op)) {
                        //说明对配置表做了删除操作，删除前的配置信息应该从before属性中获取
                        tableProcess = jsonObj.getObject("before", TableProcess.class);
                    } else {
                        //从after属性中获取对应的配置表中信息
                        tableProcess = jsonObj.getObject("after", TableProcess.class);
                    }
                    tableProcess.setOp(op);
                    return tableProcess;
                }
            }
        );
        // tableProcessDS.print(">>>");
        //TODO 7.根据配置信息到hbase中建表或者删表
        tableProcessDS = tableProcessDS.process(
            new ProcessFunction<TableProcess, TableProcess>() {
                private Connection hbaseConn;
                @Override
                public void open(Configuration parameters) throws Exception {
                    hbaseConn = HbaseUtil.getHbaseConnection();
                }

                @Override
                public void close() throws Exception {
                    HbaseUtil.closeHbaseConnection(hbaseConn);
                }

                @Override
                public void processElement(TableProcess tableProcess, Context ctx, Collector<TableProcess> out) throws Exception {
                    //获取对配置表的操作类型
                    String op = tableProcess.getOp();
                    //获取hbase中的表名
                    String sinkTable = tableProcess.getSinkTable();
                    //获取列族
                    String[] sinkFamily = tableProcess.getSinkFamily().split(",");

                    if("d".equals(op)){
                        //说明从配置表中删除了一条数据，将对应的维度表从hbase中删除
                        HbaseUtil.dropTable(hbaseConn, GmallConfig.HBASE_NAMESPACE,sinkTable);
                    }else if("c".equals(op)||"r".equals(op)){
                        //说明从添加或者读取了一条配置数据，在hbase中创建表
                        HbaseUtil.createTable(hbaseConn,GmallConfig.HBASE_NAMESPACE,sinkTable,sinkFamily);
                    }else{
                        //说明对配置表进行了更新操作，先删后创建
                        HbaseUtil.dropTable(hbaseConn, GmallConfig.HBASE_NAMESPACE,sinkTable);
                        HbaseUtil.createTable(hbaseConn,GmallConfig.HBASE_NAMESPACE,sinkTable,sinkFamily);
                    }
                    out.collect(tableProcess);
                }
            }
        );
        //TODO 8.对配置流进行广播--广播流
        MapStateDescriptor<String, TableProcess> mapStateDescriptor
            = new MapStateDescriptor<String, TableProcess>("mapStateDescriptor",String.class,TableProcess.class);
        BroadcastStream<TableProcess> broadcastDS = tableProcessDS.broadcast(mapStateDescriptor);

        //TODO 9.将主流业务数据和广播流配置数据进行关联--connect
        BroadcastConnectedStream<JSONObject, TableProcess> connectDS
            = jsonObjDS.connect(broadcastDS);

        //TODO 10.对关联后的流进行处理 --过滤出维度数据
        SingleOutputStreamOperator<JSONObject> dimDS = connectDS.process(
            new TableProcessFunction(mapStateDescriptor)
        );
        //TODO 11.将维度数据写到Hbase中
        dimDS.print(">>>");
        dimDS.addSink(new DimSinkFunction());
    }
}
